var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var Goods = require('../models/goods')
var connection = mongoose.connect('mongodb://127.0.0.1:27017/test', {
	useNewUrlParser: true
})

mongoose.connection.on('connected', () => {
	console.log('success');
})
mongoose.connection.on('error', () => {
	console.log('erroe');
})
mongoose.connection.on('disconnected', () => {
	console.log('disconnectioned');
})
router.get('/', (req, res, next) => {
	let page = req.param("page")
	let pageSize = parseInt(req.param("pageSize"))
	let priceLev = req.param("priceLev")
	let sort = req.param("sort")
	let skip = (page - 1) * pageSize
	let params = {}

	var priceGt = '',
		priceLt = ''
	if (priceLev !== "all") {
		switch (priceLev) {
			case '0':
				priceGt = 0;
				priceLt = 100;
				break;
			case '1':
				priceGt = 100;
				priceLt = 500;
				break;
			case '2':
				priceGt = 500;
				priceLt = 1000;
				break;
			case '3':
				priceGt = 1000;
				priceLt = 5000;
				break;
		}
		params = {
			salePrice: {
				$gt: priceGt,
				$lte: priceLt
			}
		}
	}
	console.log(priceGt, priceLt);
	Goods.find(params).skip(skip).sort({
		'salePrice': sort
	}).limit(pageSize).exec(function(err, docs) {
		if (err) {
			res.json({
				status: 1,
				msg: err.mssage
			})
		} else {
			res.json({
				status: 0,
				msg: '',
				result: {
					count: docs.length,
					list: docs
				}
			})
		}
	})
})
//加入购物车
router.post('/addCart', (req, res, next) => {
	var userId = "123";
	var productId = req.body.productId;
	var User = require('../models/user');
	User.findOne({
		userId
	}, (err, userDoc) => {
		if (err) {
			res.json({
				status: "1",
				msg: err.message
			})
		} else {
			if (userDoc) {
				let goodsItem = "";
				userDoc.cartList.forEach((item, index) => {
					if (item.productId == productId) {
						goodsItem = item
						item.productNum++
					}
				})
				if (goodsItem) {
					userDoc.save((err2, doc2) => {
						if (err2) {
							res.json({
								status: "1",
								msg: err2.message
							})
						} else {
							res.json({
								status: "0",
								msg: "",
								result: 'suc'
							})
						}
					})
					return false
				}
				Goods.findOne({
					productId
				}, (err1, goodsDoc) => {
					if (err1) {
						res.json({
							status: "1",
							msg: err1.message
						})
					} else {
						if (goodsDoc) {
							goodsDoc.productNum = "1";
							goodsDoc.checked = "1";
							userDoc.cartList.push(goodsDoc)
							userDoc.save((err2, doc2) => {
								if (err2) {
									res.json({
										status: "1",
										msg: err2.message
									})
								} else {
									res.json({
										status: "0",
										msg: "",
										result: 'suc'
									})
								}
							})
						}
					}
				})
			}
		}
	})

})
module.exports = router